﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Cocon90.Lib.Web
{
    /// <summary>
    /// 辅助返回响应信息
    /// </summary>
    public class responseHelper
    {

        /// <summary>
        /// 发给客户端指定Json格式字符串的响应信息。如 var message = "{success: true}";
        /// </summary>
        public static void writeMessage(HttpContext context, string message)
        {
            lock (context)
            {
                context.Response.Write(jsonHelper.jsonString(message));
                context.Response.Flush();
            }
        }
        /// <summary>
        /// 发给客户端Object序列化后的对象;
        /// </summary>
        public static void writeObject(HttpContext context, object obj)
        {
            lock (context)
            {
                context.Response.Write(jsonHelper.jsonObject(obj));
                context.Response.Flush();

            }
        }
        /// <summary>
        /// 发给客户端Json后的一个DataTable
        /// </summary>
        public static void writeTable(HttpContext context, System.Data.DataTable dt, int total)
        {
            responseHelper.writeObject(context, jsonHelper.JsonTable(dt, total));
        }
        /// <summary>
        /// 发给客户端成功的Json信息(success:true)
        /// </summary>
        public static void writeSuccessMessage(HttpContext context)
        {
            var message = "{success: true}";
            writeMessage(context, message);
        }
        /// <summary>
        /// 发给客户端失败的Json信息，同时指定失败原因。(success: false,errormsg:'失败的消息')
        /// </summary>
        public static void writeFailureMessage(HttpContext context, string errormsg)
        {
            var message = "{success: false,errormsg:'" + errormsg + "'}";
            writeMessage(context, message);
        }
        /// <summary>
        /// 快捷发给客户端增删改时的消息。row为受影响行 （row>0则success:true,row==-2则返回无权限,其它则返回失败的消息）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="row"></param>
        public static void putIDUMessage(HttpContext context, int row)
        {
            if (row > 0)
                responseHelper.writeSuccessMessage(context);
            else if (row == -2)
                responseHelper.writeFailureMessage(context, "用户无此操作权限！");
            else
                responseHelper.writeFailureMessage(context, "数据库的操作没有生效，请检查您的数据，然后重试！");
        }

    }

}
